<template>
  <div :data-theme="theme" class="app-root">
    <header class="app-header">
      <h1>Todo List</h1>
      <button class="theme-toggle" @click="toggleTheme">
        <el-icon><component :is="theme === 'light' ? Moon : Sunny" /></el-icon>
      </button>
    </header>
    <main class="app-main">
      <todo-input @add="addTodo" />
      <filter-bar v-model="filter" />
      <todo-list
        :todos="filteredTodos"
        @toggle="toggleTodo"
        @delete="deleteTodo"
      />
      <todo-stats :todos="todos" />
    </main>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import TodoInput from '../components/TodoInput.vue'
import TodoList from '../components/TodoList.vue'
import TodoStats from '../components/TodoStats.vue'
import FilterBar from '../components/FilterBar.vue'
import { Sunny, Moon } from '@element-plus/icons-vue'
import { fetchTodos, addTodo as apiAddTodo, updateTodo as apiUpdateTodo, deleteTodo as apiDeleteTodo } from '../api'

const theme = ref('light')
const todos = ref([])
const filter = ref('all')

const filteredTodos = computed(() => {
  if (filter.value === 'all') return todos.value
  if (filter.value === 'completed') return todos.value.filter(t => t.isCompleted)
  if (filter.value === 'active') return todos.value.filter(t => !t.isCompleted)
  return todos.value
})

function toggleTheme() {
  theme.value = theme.value === 'light' ? 'dark' : 'light'
  document.documentElement.setAttribute('data-theme', theme.value)
}

function addTodo(value) {
  if (!value) return
  apiAddTodo(value).then(res => {
    todos.value.push(res.data)
  })
}

function toggleTodo(id) {
  apiUpdateTodo(id).then(res => {
    const idx = todos.value.findIndex(t => t.id === id)
    if (idx !== -1) todos.value[idx] = res.data
  })
}

function deleteTodo(id) {
  apiDeleteTodo(id).then(() => {
    todos.value = todos.value.filter(t => t.id !== id)
  })
}

onMounted(() => {
  document.documentElement.setAttribute('data-theme', theme.value)
  fetchTodos().then(res => {
    todos.value = res.data
  })
})
</script>

<style scoped>
@import '../styles/theme.css'; /* 注意路径调整 */

.app-root {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--bg);
  transition: background var(--transition);
}
.app-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 32px 0 16px 0;
  max-width: 600px;
  margin: 0 auto;
}
.app-header h1 {
  font-size: 2.2rem;
  font-weight: 700;
  letter-spacing: 2px;
}
.theme-toggle {
  background: var(--card-bg);
  border: none;
  border-radius: 50%;
  box-shadow: var(--shadow);
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background var(--transition);
}
.app-main {
  flex: 1;
  max-width: 600px;
  margin: 0 auto;
  padding: 24px 0 0 0;
  display: flex;
  flex-direction: column;
  gap: 18px;
}
</style> 